<template>
  <div>
    <!--增加,修改,复制对话框 -->
    <el-dialog v-dialog-drag :visible.sync="isVisible1" width="50%">
      <span slot="title" style="font-size: large" v-if="dialogType === 'update'">修改角色</span>
      <span slot="title" style="font-size: large" v-else>增加角色</span>
      <el-form ref="roleForm" :model="roleDTO" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleDTO.name" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="角色编号" prop="code">
          <el-input v-model="roleDTO.code" placeholder="请输入角色编号" @blur="validateRoleCode" />
        </el-form-item>
        <el-form-item label="角色备注">
          <el-input v-model="roleDTO.remark" placeholder="请输入角色备注"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="roleDTO.status">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-top: 50px;text-align: right">
          <el-button @click="handleCancelEvent">取消</el-button>
          <el-button :disabled="!isValid" type="primary" @click="handleOkEvent">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-dialog-drag :visible.sync="isVisible2" width="60%">
      <span slot="title" style="font-size: large">
         用户分配
      </span>
      <el-form :inline="true" style="margin-top: 5px; margin-left: 5px;">
        <el-form-item label="用户名称">
          <el-input v-model="searchForm.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button type="primary" @click="handleUserSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="userList"
        :data="userList"
        :empty-text="'暂无数据'"
        height="100%"
        v-loading="listLoading"
        style="margin-top: 20px;max-height: 300px;overflow: hidden;overflow-y: auto"
        element-loading-text="Loading"
      >
        <el-table-column  type="selection" align="center" width="30"/>
        <el-table-column prop="code" align="center" label="用户工号">
        </el-table-column>
        <el-table-column prop="name" align="center" label="用户名">
        </el-table-column>
        <el-table-column prop="companyName" align="center" label="公司">
        </el-table-column>
        <el-table-column prop="orgName" align="center" label="部门">
        </el-table-column>
        <el-table-column v-if="false" prop="id" align="center" label="用户id"/>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        style="text-align: center; margin-top: 20px;"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-form ref="roleForm" :model="roleDTO" style="margin-top: 50px;text-align: right">
        <el-form-item>
          <el-button @click="handleCancelEvent">取消</el-button>
          <el-button type="primary" @click="handleOkEvent">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-dialog-drag :visible.sync="isVisible3" width="65%">
      <span slot="title" v-if="dialogType === 'resource'">
        当前操作的角色：{{this.roleDTO.name}}
      </span>
      <span slot="title" v-if="dialogType === 'view'" style="font-size: large">
         查看权限
      </span>
      <div style="border: 1px solid #dcdfe6; border-radius: 5px; padding: 10px;max-height: 230px;overflow: hidden;overflow-y: auto">
        <!--查看权限和资源分配树形结构-->
        <el-tree
          :empty-text="'暂无数据'"
          :data="treeData"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
         >
        </el-tree>
      </div>
      <div style="border: 1px solid #dcdfe6; border-radius: 5px; padding: 10px;margin-top: 20px">
        <el-table
          ref="coList"
          :empty-text="'暂无数据'"
          v-loading="listLoading"
          :data="coList"
          element-loading-text="Loading"
          style="max-height: 200px;overflow: hidden;overflow-y: auto"
          height="100%"
        >
          <el-table-column v-if="dialogType === 'resource'" type="selection" :reserve-selection="true" align="center" width="30"/>
          <el-table-column align="center" prop="code" label="公司编号">
          </el-table-column>
          <el-table-column align="center" prop="name" label="公司名称">
          </el-table-column>
          <el-table-column v-if="false" align="center" prop="id" label="公司id"/>
        </el-table>
        <el-pagination
          style="text-align: center; margin-top: 20px;"
          :current-page="page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div style="margin-top: 20px;text-align: right">
      <el-form ref="roleForm" :model="roleDTO">
        <el-form-item v-if="dialogType === 'resource'">
          <el-button @click="handleCancelEvent">取消</el-button>
          <el-button type="primary" @click="handleOkEvent">确定</el-button>
        </el-form-item>
        <el-form-item v-if="dialogType === 'view'">
          <el-button type="primary" @click="handleCancelEvent">取消</el-button>
        </el-form-item>
      </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@/utils/directives'// 弹窗拖拽
import {
  add,
  assignCompany,
  assignUser,
  checkRoleCode,
  getById,
  pageCompany,
  pageUser,
  update,
  getTreeData,
  assignResource
} from '@/api/role'
import {mapActions} from "vuex";

export default {
  name: 'RoleDialog',
  inject: ['reload'],
  props: {
    dialogType: String
  },
  data() {
    return {
      searchForm:{
        name:''
      },
      userList: [],
      coList:[],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      resourceIds:[],
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0,
      listLoading: false,
      isVisible1: false,
      isVisible2: false,
      isVisible3: false,
      roleDTO: {
        id:'',
        name: '',
        code: '',
        remark: '',
        status:'',
        tenantId:'',
        orgId:'',
        companyId:'',
        createdTime:'',
        createdBy:''
      },
      selectedCompanyIds: [],
      rowSelectFlag:false,
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 32, message: '长度不超过 32 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色编号', trigger: 'blur' },
          { max: 32, message: '长度不超过 32 个字符', trigger: 'blur' }
        ]
      },
      isValid:true
    }
  },
  created() {
    this.roleDTO = {};
  },
  mounted() {
    this.initUi()
  },
  methods: {
    ...mapActions(['updateSelectedUserIds']),
    ...mapActions(['updateSelectedCompanyIds']),
    validateRoleCode() {
      // 检查角色编号是否重复
      checkRoleCode(this.roleDTO.code).then(response => {
        if (response.data === true) {
          this.$message.error('角色编号已存在');
          this.isValid = false;
        } else {
          this.isValid = true;
        }
      }).catch(error => {
        console.error('验证角色编号时出错:', error);
      });
    },
    getTreeData(){
      getTreeData(this.roleDTO.id).then(response => {
        if (response.data) {
          this.treeData = [];
          for(let i=0;i<response.data.length;i++){
            this.treeData.push(response.data[i].children[0]);
          }
          console.log(this.treeData);

        } else {
          this.$message.error('资源树加载失败');
        }
      }).catch(error => {
        console.log('资源树查询出错:',error);
      })
    },
    handleOkEvent() {
      this.$nextTick(() => {
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add' || this.dialogType === 'copy') {
              // 执行添加角色操作
              this.insertRole(this.roleDTO);
              this.isVisible1 = false;
            } else if (this.dialogType === 'update') {
              // 执行修改角色操作
              this.updateRole(this.roleDTO);
              this.isVisible1 = false;
            } else if(this.dialogType === 'user') {
              // 获取选中的用户
              const selectedUsers = this.$refs.userList.selection;
              const userIds = selectedUsers.map(row => row.id)
              if (selectedUsers.length === 0) {
                this.$message.warning('请选择要分配的用户');
                return;
              }
              // console.log(userIds);
              this.$store.dispatch('updateSelectedUserIds', userIds)

              this.handleAssignUser();

              this.isVisible2 = false;
            } else if(this.dialogType === 'view') {
              this.isVisible3 = false;
            } else if(this.dialogType === 'resource'){

              this.resourceIds = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
              // 获取选中的资源
              const selectedResources = this.$refs.tree.getCheckedNodes();
              if (selectedResources<=0) {
                this.$message.warning('请选择要分配的资源');
                return;
              }
              //获取选中的公司
              const selectedCompany = this.$refs.coList.selection;
              const companyIds = selectedCompany.map(row => row.id);
              if (selectedCompany.length === 0) {
                this.$message.warning('请选择要分配的公司');
                return;
              }

              this.$store.dispatch('updateSelectedCompanyIds', companyIds);
              console.log(this.$store.state.selectedCompanyIds);
              this.handleAssignResource();
              this.handleAssignCompany();
              this.isVisible3 = false;
            }
          } else {
            return false ;// 表单验证不通过，不执行操作
          }
        })
      })
    },
    fetchData() {
      this.listLoading  = true;
      const userPageQueryDTO = {
        roleIds: this.$store.state.selectedRoleIds.join(','),
        name: this.searchForm.name,
        page: this.page,
        pageSize: this.pageSize,
      };
      pageUser(userPageQueryDTO)
          .then(response => {
            this.userList = response.data.records;
            this.total = response.data.total;
          })
          .catch(error => {
            console.error('获取数据出错', error);
          })
          .finally(() => {
            this.listLoading = false; // 数据加载完成
          });
    },
    fetchCompanyData() {
      this.listLoading  = true;
      const companyPageQuery = {
        roleId : this.roleDTO.id,
        page: this.page,
        pageSize: this.pageSize,
      };
      pageCompany(companyPageQuery)
        .then(response => {
          this.coList = response.data.records;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据出错', error);
        })
        .finally(() => {
          this.listLoading = false; // 数据加载完成
        });
    },
    handleUserSearch(){
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      if (this.dialogType === 'user' ) {
        this.fetchData();
      } else {
        this.fetchCompanyData();
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      if (this.dialogType === 'user' ) {
        this.fetchData();
      } else {
        this.fetchCompanyData();
      }
    },
    insertRole(roleDTO) {
      add(roleDTO)
          .then(response => {
            if (response.data === true) {
              this.$message.success("添加成功");
              this.$emit("fetch");
            } else {
              if(response.msg){
                this.$message.warning(response.msg);
              }else {
                this.$message.warning("添加失败");
              }
            }
          })
          .catch(err => {
            this.$message.warning("添加角色发生异常, err: " + err);
          });
    },
    updateRole(roleDTO) {
      update(roleDTO)
          .then(response => {
            if (response.code === 1) {
              this.$message.success("更新成功");
              this.$emit("fetch");
            } else {
              this.$message.warning("更新失败");
            }
          })
          .catch(err => {
            this.$message.warning("更新角色发生异常, err: " + err);
          });
    },
    handleAssignUser(){
      const userRoleDTO = {
        userIds: JSON.parse(JSON.stringify(this.$store.state.selectedUserIds)),
        roleIds: JSON.parse(JSON.stringify(this.$store.state.selectedRoleIds))
      };
      assignUser(userRoleDTO)
          .then(response => {
            if (response.code === 1) {
              this.$message.success("分配用户成功");
            } else {
              if(response.msg){
                this.$message.warning(response.msg);
              }else {
                this.$message.warning("分配用户失败");
              }
            }
          })
          .catch(err => {
            this.$message.warning("分配用户发生异常, err: " + err);
          });
    },
    handleAssignResource(){
      const roleResouceDTO = {
        roleIds: JSON.parse(JSON.stringify(this.$store.state.selectedRoleIds)),
        resourceIds: JSON.parse(JSON.stringify(this.resourceIds)),
      };
      assignResource(roleResouceDTO)
        .then(response => {
          if (response.data === true) {
            this.$message.success("分配资源成功");
          } else {
            if(response.msg){
              this.$message.warning(response.msg);
            }else {
              this.$message.warning("分配资源失败");
            }
          }
        })
        .catch(err => {
          this.$message.warning("分配资源发生异常, err: " + err);
        });
    },
    handleAssignCompany(){
      const roleCompanyDTO = {
        roleIds: JSON.parse(JSON.stringify(this.$store.state.selectedRoleIds)),
        companyIds: JSON.parse(JSON.stringify(this.$store.state.selectedCompanyIds)),
      };
      assignCompany(roleCompanyDTO)
        .then(response => {
          if (response.code === 1) {
            this.$message.success("分配公司成功");
          } else {
            if(response.msg){
              this.$message.warning(response.msg);
            }else {
              this.$message.warning("分配公司失败");
            }
          }
        })
        .catch(err => {
          this.$message.warning("分配公司发生异常, err: " + err);
        });
    },
    handleCancelEvent() {
      if (this.dialogType === 'add' || this.dialogType==='update' || this.dialogType === 'copy') {
        this.isVisible1 = false ;
      } else if (this.dialogType === 'user'){
        this.isVisible2 = false ;
      } else if (this.dialogType === 'resource' || this.dialogType === 'view') {
        this.isVisible3 = false ;
      }
    },
    onShow(row) {
      this.initUi() ;
      if (this.dialogType === 'update'||this.dialogType === 'copy') {
        getById(row.id)
            .then(role => {
              this.roleDTO ={
                id:  BigInt(role.data.id).toString(),
                name: role.data.name,
                code: role.data.code,
                remark: role.data.remark,
                status: String(role.data.status),
                tenantId: BigInt(role.data.tenantId).toString(),
                orgId: BigInt(role.data.orgId).toString(),
                companyId: BigInt(role.data.companyId).toString(),
                createdTime: role.data.createdTime,
                createdBy: role.data.createdBy,
              };
            })
            .catch(err => {
              this.$message.error('加载用户信息失败'+err);
              this.isVisible1 = false; // 加载失败时隐藏对话框
            });
      }
      // if(this.dialogType === "view"){
      //   this.roleDTO.id = row.id;
      // }
      if (this.dialogType === 'add' || this.dialogType==='update' || this.dialogType === 'copy') {
        this.isVisible1 = true;
      } else if (this.dialogType === 'user'){
        this.fetchData();
        this.isVisible2 = true ;
      } else if (this.dialogType === 'resource' || this.dialogType==='view') {
        this.roleDTO.name = row.selectedRoleNames;
        this.roleDTO.id = row.id;
        this.getTreeData();
        this.fetchCompanyData();
        this.isVisible3 = true ;
      }
      this.$refs.roleForm.resetFields();
    },
    initUi() {
      this.roleDTO = {};
    }
  }
}
</script>
<style>
.el-table::before {
  height: 0;
}
</style>
